package producerconsumer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;



public class Buffer {
	public Buffer(int lengtOfQueue) {
		this.itemQueue = new String [lengtOfQueue];
	}
	
	private final Lock lock = new ReentrantLock();
    private final Condition notFull = lock.newCondition();
    private final Condition notEmpty = lock.newCondition();
    
    private int itemQueuePosition = 0;

    // Whether there is an item in the buffer or not.
    private boolean available = false;
    // The buffered item - the value has no meaning if available is false
    
    private String [] itemQueue;

    public String take() throws InterruptedException {
        lock.lock();
        try {
            while (itemQueuePosition <= 0  ) {
                notEmpty.await();
            }
            //available = false;
            notFull.signal();
            
            itemQueuePosition--;
            return itemQueue[itemQueuePosition];
        } finally {
            lock.unlock();
        }
    }

    public void put(String item) throws InterruptedException {
        lock.lock();
        try {
            while (itemQueuePosition >= itemQueue.length ) {
                notFull.await();
            }
            
            //available = true;
            this.itemQueue[itemQueuePosition] = item;
            
            itemQueuePosition++;
            
            notEmpty.signal();
        } finally {
            lock.unlock();
        }	
    }

}